import urllib
import gdata.service
import gdata.alt.appengine

from src.Profile import Profile

from google.appengine.ext import db

class Authenticator(object):
    # constants
    TOKEN_SCOPE = "http://docs.google.com/feeds/"
    HOST_NAME = "usverg-er.appspot.com"
    BACK_HANDLER = "auth"

    #private fields
    _profile = None

    # constructor
    def __init__(self, user):
        self.user = user
        self.client = gdata.service.GDataService()
        gdata.alt.appengine.run_on_appengine(self.client)
        self.client.SetAuthSubToken(Profile.token)
    
    # getters-setters
    def _getLink(self):
        backurl = "http://" + self.HOST_NAME + "/" + self.BACK_HANDLER + "?token_scope=" + self.TOKEN_SCOPE
        return self.client.GenerateAuthSubURL(backurl, self.TOKEN_SCOPE, secure=False, session=True)
        
    def _getProfile(self):
        if self._profile:
            return self._profile
            
        profile = db.GqlQuery('SELECT * FROM Profile WHERE user = :1', self.user).get()
        if not profile:
            profile = Profile(user=self.user, token="")
                
        self._profile = profile
        return self._profile
        
    # public methods
    def Authenticate(self, newToken):
        self.client.SetAuthSubToken(newToken)
        self.client.UpgradeToSessionToken()
        self.Profile.token = self.client.GetAuthSubToken()
        self.Profile.put()

    #properties
    Link = property(fget=_getLink)
    Profile = property(fget=_getProfile)
